//
//  LXDialRulerView.m
//  ibgs_patients
//
//  Created by xiao.zhao@lachesis-mh.com on 15/12/29.
//  Copyright © 2015年 xiao.zhao@lachesis-mh.com. All rights reserved.
//

#import "LXDialRulerView.h"
#import "LXDialRulerScrollView.h"

#define SHEIGHT 8 // 中间指示器顶部闭合三角形高度

@interface LXDialRulerView ()<UIScrollViewDelegate>

@property (nonatomic, strong) LXDialRulerScrollView *rulerScrollView;

@property (nonatomic, strong) CAShapeLayer *borderLayer;
@property (nonatomic, strong) CAShapeLayer *shapeLayerLine;

@property (nonatomic, assign) BOOL isAdd;

@end

@implementation LXDialRulerView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor whiteColor];
        
        self.rulerScrollView.rulerHeight = frame.size.height;
        self.rulerScrollView.rulerWidth = frame.size.width;
    }
    return self;
}

-(void)layoutSubviews
{
    [super layoutSubviews];
    
    self.rulerScrollView.rulerHeight = self.bounds.size.height;
    self.rulerScrollView.rulerWidth = self.bounds.size.width;
    if(self.rulerScrollView.rulerHeight > 0 && !self.isAdd)
    {
        self.isAdd = YES;
        [_rulerScrollView drawRuler];
    }
    
    _borderLayer.frame = self.bounds;
    CGPathRef path = [UIBezierPath bezierPathWithRoundedRect:_borderLayer.bounds cornerRadius:6.0f].CGPath;
    _borderLayer.path = path;
    
    NSUInteger ruleHeight = 20; // 文字高度
    CGMutablePathRef pathLine = CGPathCreateMutable();
    CGPathMoveToPoint(pathLine, NULL, self.frame.size.width / 2, self.frame.size.height - DISTANCETOPANDBOTTOM - ruleHeight);
    CGPathAddLineToPoint(pathLine, NULL, self.frame.size.width / 2, DISTANCETOPANDBOTTOM);
    
    _shapeLayerLine.path = pathLine;
}

- (void)showRulerScrollViewWithMin:(NSUInteger)min
                               Max:(NSUInteger)max
                             average:(NSNumber *)average
                        currentValue:(CGFloat)currentValue
                           smallMode:(BOOL)mode {
    NSAssert(_rulerScrollView != nil, @"***** 调用此方法前，请先调用 initWithFrame:(CGRect)frame 方法初始化对象 rulerScrollView\n");
    NSAssert(currentValue <= [average floatValue] * max, @"***** currentValue 不能大于直尺最大值（count * average）\n");
    _rulerScrollView.rulerAverage = average;
    _rulerScrollView.rulerMin = min;
    _rulerScrollView.rulerMax = max;
    _rulerScrollView.rulerValue = currentValue;
    _rulerScrollView.mode = mode;
    [self addSubview:_rulerScrollView];
    [self drawRacAndLine];
}

- (LXDialRulerScrollView *)rulerScrollView
{
    if(!_rulerScrollView)
    {
        _rulerScrollView = [[LXDialRulerScrollView alloc]init];
        _rulerScrollView.delegate = self;
        _rulerScrollView.showsHorizontalScrollIndicator = NO;
    }
    
    return _rulerScrollView;
}

-(void)scrollToValue:(CGFloat)value
{
    CGFloat oX = value - 0.6;
    
    if ([self valueIsInteger:_rulerScrollView.rulerAverage]) {
        oX = [self notRounding:oX afterPoint:0];
    }
    else {
        oX = [self notRounding:oX afterPoint:1];
    }
    
    CGFloat offX = (oX / ([_rulerScrollView.rulerAverage floatValue])) * DISTANCEVALUE + DISTANCELEFTANDRIGHT - self.frame.size.width / 2;
    [UIView animateWithDuration:.2f animations:^{
        _rulerScrollView.contentOffset = CGPointMake(offX, 0);
    }];

}

#pragma mark - ScrollView Delegate
- (void)scrollViewDidScroll:(LXDialRulerScrollView *)scrollView {
    CGFloat offSetX = scrollView.contentOffset.x + self.frame.size.width / 2 - DISTANCELEFTANDRIGHT;
    CGFloat ruleValue = (offSetX / DISTANCEVALUE  + scrollView.rulerMin) * [scrollView.rulerAverage floatValue];
    if (ruleValue < scrollView.rulerMin * [scrollView.rulerAverage floatValue]) {
        return;
    } else if (ruleValue > scrollView.rulerMax * [scrollView.rulerAverage floatValue]) {
        return;
    }
    if (self.delegate) {
        if (!scrollView.mode) {
            scrollView.rulerValue = ruleValue;
        }
        scrollView.mode = NO;
        [self.delegate rulerView:self didScrollToValue:scrollView.rulerValue];
    }
}

- (void)scrollViewDidEndDecelerating:(LXDialRulerScrollView *)scrollView {
    [self animationRebound:scrollView];
}

- (void)scrollViewDidEndDragging:(LXDialRulerScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    [self animationRebound:scrollView];
}

- (void)animationRebound:(LXDialRulerScrollView *)scrollView {
    CGFloat offSetX = scrollView.contentOffset.x + self.frame.size.width / 2 - DISTANCELEFTANDRIGHT;
    CGFloat oX = (offSetX / DISTANCEVALUE) * [scrollView.rulerAverage floatValue];

    if ([self valueIsInteger:scrollView.rulerAverage]) {
        oX = [self notRounding:oX afterPoint:0];
    }
    else {
        oX = [self notRounding:oX afterPoint:1];
    }

    CGFloat offX = (oX / ([scrollView.rulerAverage floatValue])) * DISTANCEVALUE + DISTANCELEFTANDRIGHT - self.frame.size.width / 2;
    [UIView animateWithDuration:.2f animations:^{
        scrollView.contentOffset = CGPointMake(offX, 0);
    }];
}

- (void)drawRacAndLine
{
    //圆角边框
    self.borderLayer = [CAShapeLayer layer];
    _borderLayer.strokeColor = [UIColor colorWithHexString:@"bfbfbf"].CGColor;
    _borderLayer.fillColor = [UIColor clearColor].CGColor;
    _borderLayer.lineWidth = 0.5f;
    _borderLayer.lineJoin = kCALineJoinRound;
    [self.layer addSublayer:_borderLayer];
    
    //    // 渐变
    //    CAGradientLayer *gradient = [CAGradientLayer layer];
    //    gradient.frame = self.bounds;
    //
    //    gradient.colors = @[(id)[[UIColor whiteColor] colorWithAlphaComponent:1.f].CGColor,
    //                        (id)[[UIColor whiteColor] colorWithAlphaComponent:0.0f].CGColor,
    //                        (id)[[UIColor whiteColor] colorWithAlphaComponent:1.f].CGColor];
    //
    //    gradient.locations = @[[NSNumber numberWithFloat:0.0f],
    //                           [NSNumber numberWithFloat:0.6f]];
    //
    //    gradient.startPoint = CGPointMake(0, .5);
    //    gradient.endPoint = CGPointMake(1, .5);
    //
    //    CGMutablePathRef pathArc = CGPathCreateMutable();
    //
    //    CGPathMoveToPoint(pathArc, NULL, 0, DISTANCETOPANDBOTTOM);
    //    CGPathAddQuadCurveToPoint(pathArc, NULL, self.frame.size.width / 2, - 20, self.frame.size.width, DISTANCETOPANDBOTTOM);
    //
    //    shapeLayerArc.path = pathArc;
    //    [self.layer addSublayer:shapeLayerArc];
    //    [self.layer addSublayer:gradient];
    
    // 红色指示器
    self.shapeLayerLine = [CAShapeLayer layer];
    _shapeLayerLine.strokeColor = kAppGreenTextColor.CGColor;
//    _shapeLayerLine.fillColor = kAppThemeColor.CGColor;
    _shapeLayerLine.lineWidth = 1.f;
    _shapeLayerLine.lineCap = kCALineCapSquare;
    
    [self.layer addSublayer:_shapeLayerLine];
}

#pragma mark - tool method
- (CGFloat)notRounding:(CGFloat)price afterPoint:(NSInteger)position {
    NSDecimalNumberHandler *roundingBehavior = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundPlain scale:position raiseOnExactness:NO raiseOnOverflow:NO raiseOnUnderflow:NO raiseOnDivideByZero:NO];
    NSDecimalNumber *ouncesDecimal;
    NSDecimalNumber *roundedOunces;
    ouncesDecimal = [[NSDecimalNumber alloc] initWithFloat:price];
    roundedOunces = [ouncesDecimal decimalNumberByRoundingAccordingToBehavior:roundingBehavior];
    return [roundedOunces floatValue];
}

- (BOOL)valueIsInteger:(NSNumber *)number {
    NSString *value = [NSString stringWithFormat:@"%f",[number floatValue]];
    if (value != nil) {
        NSString *valueEnd = [[value componentsSeparatedByString:@"."] objectAtIndex:1];
        NSString *temp = nil;
        for(int i =0; i < [valueEnd length]; i++)
        {
            temp = [valueEnd substringWithRange:NSMakeRange(i, 1)];
            if (![temp isEqualToString:@"0"]) {
                return NO;
            }
        }
    }
    return YES;
}

@end
